<template>
	<view>

		<!-- 截至时间 和 进度拖动栏 -->
		<movable-area class="movable_area" @longpress="longPress" @click="chooseDeadline()">
			<!-- 提示的文字 -->
			<view class="movable_text" :class="{'movable_done': lineFirstMode === 'setDdl' && percentShow === 100, 'movable_expired': deadline && lineFirstMode === 'setDdl' && isPlanExpired(deadline) && percentShow !== 100}">
				{{lineFirstMode === 'setDdl' ? deadline ? `${deadline} 截至` : '请选择截止时间' : percentShow + '%'}}
			</view>
			<!-- 滑块区域 -->
			<movable-view 
				direction="horizontal" 
				@change="blockOnChange" 
				class="movable_block" 
				:x="x" 
				:damping="10"
				:disabled="lineFirstMode !== 'setProgress'">
			</movable-view>
			<!-- 进度条显示 -->
			<view class="progress" :style="{width: percentShow + '%'}"></view>
		</movable-area>
	
		<!-- deadlinePicker -->
		<w-picker
			:visible.sync="visible"
			mode="shortTerm"
			:current="true"
			:expand="expand"
			@confirm="pickerOnConfirm($event,'shortTerm')"
			ref="picker" 
		></w-picker>
	
		<!-- 分类标签选择栏 -->
		<view class="choose_tag" @click="popupOpen">
		
			<view v-if="tagList.filter(filterItem => filterItem.checked === true).length === 0">选择分类标签</view>
		
			<view v-else class="tag_selected" v-for="item in tagList.filter(filterItem => filterItem.checked === true)" :style="{'background-color': item.color}">
				{{'#' + item.tagName}}
			</view>
		
		</view>
		
		<!-- 分类标签选择弹框	 -->
		<popup type="center" ref="popup" :maskClick="false">
			<view class="popcontainer">
				<view class="title">添加标签</view>
				
				<!-- 多选区 -->
				<checkbox-group @change="checkboxChange">
				    <label class="checkbox_item" v-for="item in tagList" >
				        <view>
				            <checkbox :value="item.id" :checked="item.checked" color="#617FDE" style="transform:scale(0.6)"/>
				        </view>
				        <view class="checkbox_item_name">{{item.tagName}}</view>
				    </label>
				</checkbox-group>
				
				<view class="cancel_btn_box">
					<view class="cancel_btn" @click="tagPopupCancel">取消</view>
					<view class="cancel_btn confirm_btn" @click="tagPopupConfirm">确认</view>
				</view>
			</view>
		</popup>	
				
		<!-- 标题栏 -->
		<view class="plan_title">
			<text>标题：</text>
			<input type="text" placeholder="请输入计划标题" maxlength="30" v-model.trim="planTitle">
		</view>
		
		<!-- 计划内容富文本区域 -->
		<view class="plan_content">
			<view class="plan_content_text">内容：</view>
			<editor 
			id="editor"
			@ready="onEditorReady" 
			@input="editorInput" 
			placeholder="请输入计划内容"></editor>
		</view>
		
		<!-- 完成、取消按钮 -->
		<view class="btn_placeholder"></view>
		<view class="btn_area">
			<view class="btn_item btn_delete" @click="deletePlan()" :class="{'btn_delete_hidden' : mode === 'add'}">删除</view>
			
			<view class="btn_area_right">
				<view class="btn_item btn_left" @click="$navigateBack()">取消</view>
				<view class="btn_item btn_right" @click="submitPlanTable()">完成</view>
			</view>
			
		</view>
						
	</view>
	
</template>

<script>
	import popup from '@/components/uni-popup/uni-popup.vue'
	import wPicker from "@/components/w-picker/w-picker.vue";
	import { isPlanExpired, getNowDateStrFull } from '@/utils/planDateHandle.js'
	
	export default {
		components:{
		    wPicker,
			popup
		},
		data() {
			return {
				// 页面初始化
				mode: '', // 页面类型（添加或编辑）
				duration: '', // 期限（短期或长期）
				planId: '',

				// 截止时间 和 计划进度部分 
				lineFirstMode: 'setDdl', // setProgress和setDdl两个模式
				x: 0,
				blockWidth: 0,
				movableWidth: 0,
				percentShow: 0,
				visible: false,		// picker显示与隐藏
				deadline: '',		// 计划截至时间
				
				// 分类标签部分
				tagList: [],
				tagListBackup: [],		// tagList备份

				// 页面标题
				planTitle: '',
				
				// 富文本内容
				contentHTML: '',
				editorCtx: '',
				
			};
		},
		computed: {
			// 截至时间从今天往后推多少天，短期7天，长期30天
			expand() {
				if(this.duration === 'short') {
					return '7'
				}else if(this.duration === 'long') {
					return '30'
				}
			},
		},
		onReady() {

			this.getDomInfo()

			

		},
		async onLoad(query) {
			this.mode = query.mode
			this.duration = query.duration
			
			
			this.pageInit()
			
			await this.getTagList()
			
			if(query.planid) {
				this.planId = query.planid
				this.getPlanInfo()
			}

		},
		methods: {
			getNowDateStrFull,
			// 判断计划是否过期
			isPlanExpired,
			// 获取标签列表
			getTagList() {
				return this.$http_json({
					url: "/api/tag/list",
					method: "get",
					loading: false,
					params: {
						userId: this.$getMemoryPmt('userInfo').id
					}
				}).then(result => {
					console.log(result)
					this.tagList = result.data
					// todo
				})
			},
			// 表单验证
			submitValidate() {
				if(!this.deadline || !this.planTitle || !this.contentHTML) {
					uni.showToast({
						icon: 'none',
						title: '请完善表单信息'
					})
					return false
				} 
				
				return true
			},
			// 删除计划
			deletePlan() {
				uni.showModal({
				    title: '提示',
				    content: '是否要删除该计划？',
				    success: res => {
				        if (res.confirm) {
				            console.log('用户点击确定');			
							
							this.$http_json({
								url: "/api/plan/delete",
								method: "post",
								data: {
									planId: this.planId
								}
							}).then(result => {
								console.log(result)
								
								this.$showToast({
									title: '删除成功'
								})
								
								setTimeout(() => {
									this.$navigateBack()
								}, 1000)
								// todo
							})

				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
			},
			// 计划表单提交
			submitPlanTable() {
				if(!this.submitValidate()) return
				
				// 处理选中标签的id数组
				let tagSelectedList = []
				for(let key in this.tagList) {
					if(this.tagList[key].checked === true) {
						tagSelectedList.push(this.tagList[key].id)
					}
				}
				
				if(this.mode === 'add') {
					
					this.$http_json({
						url: "/api/plan/new",
						method: "post",
						data: {
							title: this.planTitle,
							content: this.contentHTML,
							duration: this.duration,
							deadline: this.deadline,
							createdAt: this.getNowDateStrFull(),
							progress: this.percentShow,
							userId: this.$getMemoryPmt('userInfo').id,
							tagList: tagSelectedList,
						}
					}).then(result => {
						
						console.log(result)

						uni.showToast({
							icon: 'success',
							title: '添加成功'
						})
						
						setTimeout(() => {
							this.$navigateBack()
						}, 1000)
					})
				}
				else if(this.mode === 'update') {
					
					this.$http_json({
						url: "/api/plan/update",
						method: "post",
						data: {
							planId: this.planId,
							title: this.planTitle,
							content: this.contentHTML,
							deadline: this.deadline,
							progress: this.percentShow,
							tagList: tagSelectedList,
						}
					}).then(result => {
						
						console.log(result)
					
						uni.showToast({
							icon: 'success',
							title: '修改成功'
						})
						
						setTimeout(() => {
							this.$navigateBack()
						}, 1000)
					})	
				}
					
			},
			// 富文本 回显初始化
			onEditorReady() {
			    uni.createSelectorQuery().select('#editor').context((res) => {
			        this.editorCtx = res.context
					
					this.editorCtx.setContents({
						html:this.contentHTML,
						success:(res)=> {
							// console.log(res)
						},
						fail:(res)=> {
							console.log(res)
						},
					})
					
			    }).exec()
				
			},
			// 计划 富文本内容回调
			editorInput(e) {
				this.contentHTML = e.detail.html
			},
			
			// 处理页面请求接口相关逻辑
			getPlanInfo() {
				// 先获取全部标签列表接口,then里再写获取计划详情接口
				this.$http_json({
					url: "/api/plan/detail",
					method: "get",
					params: {
						planId: this.planId
					}
				}).then(result => {
					console.log(result.data)
					this.deadline = result.data.deadline
					this.planTitle = result.data.title
					
					setTimeout(() => {
						this.percentConvertPos(result.data.progress)
					}, 1000)
					
					
					this.contentHTML = result.data.content
					this.onEditorReady()
					
					this.initSelectedTag(result.data.tagList)
				})
				
			},
			// 标签popup弹出框  取消事件
			tagPopupCancel() {
				// 还原成 选择前的数组
				this.tagList = JSON.parse(JSON.stringify(this.tagListBackup))
				// 清空taglist备份
				this.tagListBackup = []
				this.$refs.popup.close()
			},
			// 标签popup弹出框  确认事件
			tagPopupConfirm() {
				// 清空taglist备份
				this.tagListBackup = []
				this.$refs.popup.close()
			},
			// 标签popup弹出事件
			popupOpen() {
				// 先备份分类标签 点击前的数组
				this.tagListBackup = JSON.parse(JSON.stringify(this.tagList))
				this.$refs.popup.open()
			},
			// 标签多选栏选中回调函数
			checkboxChange(e) {
				// console.log(e)
			    let items = this.tagList,
			        values = e.detail.value;
			    for (let i = 0, lenI = items.length; i < lenI; ++i) {
			        const item = items[i]
			        if(values.includes(String(item.id))){
			            this.$set(item,'checked',true)
			        }else{
			            this.$set(item,'checked',false)
			        }
			    }
							
				console.log(this.tagList)
			},
			// 初始化计划详情 中 已选择的标签
			initSelectedTag(selectedList) {
				
				let selectedTagIdList = []
				for(let key in selectedList) {
					selectedTagIdList.push(selectedList[key].id)
				}
				
				let items = this.tagList,
				    values = selectedTagIdList;
				for (let i = 0, lenI = items.length; i < lenI; ++i) {
				    const item = items[i]
				    if(values.includes(item.id)){
				        this.$set(item,'checked',true)
				    }else{
				        this.$set(item,'checked',false)
				    }
				}
				
			},
			// 页面初始化处理
			pageInit() {
				if (this.mode === 'add' && this.duration === 'short') {
					// 加载 添加短期计划页面
					uni.setNavigationBarTitle({
						title: '添加短期计划'
					})
				} else if (this.mode === 'update' && this.duration === 'short') {
					// 加载 添加短期计划页面
					uni.setNavigationBarTitle({
						title: '编辑短期计划'
					})
				} else if (this.mode === 'add' && this.duration === 'long') {
					// 加载 添加短期计划页面
					uni.setNavigationBarTitle({
						title: '添加长期计划'
					})
				} else if (this.mode === 'update' && this.duration === 'long') {
					// 加载 添加短期计划页面
					uni.setNavigationBarTitle({
						title: '编辑长期计划'
					})
				}
			},
			// 获取 节点元素 长度信息
			getDomInfo() {
				uni.createSelectorQuery().select(".movable_block").boundingClientRect(res => {
					this.blockWidth = res.width
					console.log(this.blockWidth)
				}).exec();
				
				uni.createSelectorQuery().select(".movable_area").boundingClientRect(res => {
					this.movableWidth = res.width
					console.log(this.movableWidth)
				}).exec();
			},
			// 截至时间picker 确认回调
			pickerOnConfirm(e) {
				console.log(e)
				this.deadline = e.value
				
				// 改变期限日期的文字
			},
			// 截至时间栏点击，弹出picker
			chooseDeadline() {
				if(this.lineFirstMode !== 'setDdl') return
				this.visible = true
			},
			// 截至时间栏长按切换模式
			longPress() {
				if (this.lineFirstMode === 'setProgress') {
					this.lineFirstMode = 'setDdl'
					console.log('当前为设置期限模式')
				} else {
					this.lineFirstMode = 'setProgress'
					console.log('当前为设置进度模式')
				}
				
				uni.vibrateLong({
				    success: function () {
				        console.log('success');
				    }
				});
			},
			// 滑块移动回调
			blockOnChange(e) {

				let curPosX = e.detail.x
				this.percentShow = Math.round(curPosX / (this.movableWidth - this.blockWidth) * 100)

			},
			// 进度条回显
			percentConvertPos(perNum) {
				this.$nextTick(() => {
					this.x = perNum / 100 * (this.movableWidth - this.blockWidth)
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #FFFFFF;
	}

	.movable_area {
		width: 100%;
		height: 78rpx;
		background-color: #FFFFFF;
		position: relative;


		.movable_block {
			width: 60rpx;
			height: 100%;
			opacity: 0.2;
		}

		.progress {
			height: 100%;
			background-color: #F0F2FC;
			color: #617FDE;

		}

		.movable_text {
			position: absolute;
			height: 100%;
			display: flex;
			align-items: center;
			margin-left: 30rpx;
			font-size: 26rpx;
			color: #617FDE;
		}
		
		.movable_done {
			color: rgba(0,0,0,0.3);
		}
		
		.movable_expired {
			color: #E24844;
		}
	}

	.choose_tag {
		min-height: 78rpx;
		background-color: lightyellow;
		padding: 0 30rpx;
		font-size: 26rpx;
		
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		
		.tag_selected {
			color: #FFFFFF;
			
			height: 40rpx;
			border-radius: 20rpx;
			
			display: flex;
			align-items: center;
			
			padding: 0 14rpx;
			font-size: 24rpx;
			
			margin: 19rpx 14rpx 19rpx 0;
			
		}
	}
	
	.popcontainer {
		width: 450rpx;
		padding: 30rpx 30rpx;
		// height: 400rpx;
		background-color: #FFFFFF;
		border-radius: 12rpx;
		box-shadow: 0px 0px 14px 0px rgba(0, 0, 0, 0.12142857142857139);
		
		.title {
			font-size: 28rpx;
			border-bottom: 2rpx solid #F3F3F3;
			padding-bottom: 16rpx;
		}
		
		// checkbox多选区
		.checkbox_item {
			display: flex;
			align-items: center;
			padding: 10rpx 0;
			
			.checkbox_item_name {
				font-size: 26rpx;
				margin-left: 6rpx;
			}
		}
		
		.cancel_btn_box {
			display: flex;
			justify-content: flex-end;
			margin-top: 26rpx;
			
			.cancel_btn {
				padding: 10rpx 16rpx 10rpx 16rpx;
				
				color: #617FDE;
				font-size: 24rpx;
			}
		}
		
		.confirm_btn {
			margin-left: 24rpx;
		}
	}
	
	.plan_title {
		padding: 0 30rpx;
		display: flex;
		align-items: center;
		font-size: 28rpx;
		height: 80rpx;
		
		text {
			flex-shrink: 0;
			font-weight: bold;
		}
		
		input {
			height: 100%;
			width: 100%;
			font-weight: bold;
		}
	}
	
	.plan_content {
		padding: 0 30rpx;
		// background-color: lightblue;
		
		.plan_content_text {
			font-size: 28rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
		}
		
		editor {
			height: 700rpx;
		}
	}
	
	.btn_placeholder {
		height: 132rpx;
		width: 100%;
	}
	
	.btn_area {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
		height: 132rpx;
		
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #FFFFFF;
		z-index: 9;
		
		.btn_item {
			padding: 12rpx 28rpx;
			border-radius: 10rpx;
			font-size: 30rpx;
			
		}
		
		.btn_delete {
			color: #FFFFFF;
			background-color: #E13E39;
			margin-right: 20rpx;
		}
		
		.btn_delete_hidden {
			visibility: hidden;
		}
		
		.btn_area_right {
			display: flex;
			.btn_left {
				color: #FFFFFF;
				background-color: #B6B6B6;
				margin-right: 20rpx;
			}
			
			.btn_right {
				color: #FFFFFF;
				background-color: #617FDE;
			}
		}
	}
	
</style>
